package com.cloud.pole.msg.service.impl;

import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.Properties;

import javax.annotation.Resource;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.EnableTransactionManagement;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;

import lombok.extern.slf4j.Slf4j;

import com.ace.cache.api.CacheAPI;
import com.alibaba.fastjson.JSON;
import com.cloud.pole.common.constant.CacheConstant;
import com.cloud.pole.common.service.impl.BaseServiceImpl;
import com.cloud.pole.mapper.SmsSendHisMapper;
import com.cloud.pole.msg.biz.SmsSendHisBiz;
import com.cloud.pole.msg.biz.SmsTemplateBiz;
import com.cloud.pole.msg.config.SmsProperties;
import com.cloud.pole.msg.model.entity.SmsSend;
import com.cloud.pole.msg.model.entity.SmsSendHis;
import com.cloud.pole.msg.model.entity.SmsTemplate;
import com.cloud.pole.msg.model.enums.SmsSendStatus;
import com.cloud.pole.msg.service.SmsSendHisService;
import com.cloud.pole.msg.service.SmsSendService;
import com.cloud.pole.msg.sms.request.SmsSendRequest;
import com.cloud.pole.msg.sms.response.SmsSendResponse;
import com.cloud.pole.msg.sms.util.ChuangLanSmsUtil;

import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.NameValuePair;
import org.apache.commons.httpclient.methods.PostMethod;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

@Slf4j
@Service(value = "smsSendService")
@EnableTransactionManagement
public class SmsSendServiceImpl  implements SmsSendService{
	
	@Resource
	SmsProperties smsProperties;  
	@Autowired
	SmsSendHisBiz smsSendHisBiz; 
	@Autowired
	SmsTemplateBiz smsTemplateBiz;
	@Autowired
    private CacheAPI cacheAPI;

	/**
	 * 发送短信
	 * @param mobile
	 * @param content
	 * @return
	 */
	private boolean sendMsgPost(String mobile, String content) {
		String strStatus = "";
	    String strResultInfo = "", strResult = "";
	    int statusCode = 0;
	    boolean flag = false;
	    try{
	        HttpClient client = new HttpClient();
	        PostMethod post = new PostMethod(smsProperties.getUrl());
	        log.info("短信服务器发送手机："+mobile+" 内容："+content);
	        //在头文件中设置转码
	        post.addRequestHeader("Content-Type", "application/x-www-form-urlencoded;charset=GBK");
	        NameValuePair[] data ={
	           new NameValuePair("user_id", smsProperties.getUserid()),
	           new NameValuePair("user_pwd", smsProperties.getPassword()),
	           new NameValuePair("mobile", mobile),
	           new NameValuePair("msg_content", content),
	           new NameValuePair("corp_msg_id", ""),
	           new NameValuePair("ext", "")
	        };
	        post.setRequestBody(data);
	        client.executeMethod(post);
	        statusCode = post.getStatusCode();
	        strResultInfo = new String(post.getResponseBodyAsString().getBytes("GBK"));
	        if(strResultInfo != null){
	            strResultInfo = strResultInfo.replaceAll("\r\n", "");
	        }
	        post.releaseConnection();
	     }
	     catch(Exception ex){
	        ex.printStackTrace();
	     }
	     finally{
	         if(strResultInfo.indexOf("#") > 0 && statusCode == 200){
	        	 strResult = "OK";
	        	 strStatus = "1";
	        	 flag = true;
	         }
	         else{
	             strStatus = strResultInfo;
	             if(statusCode != 200){
	            	 strResult = "通道网络错误";
	             }
	             else{
	                 try {
	                	 strResult = shiftStatus(Integer.parseInt(strStatus));
	                 } catch (Exception ex) {
	                    ex.printStackTrace();
	                 }
	             }
	         }
	         log.info("{\"status\":\""+strStatus+"\",\"msg\":\""+strResult+"\"}");
	     }
	     return flag;
	}

	private static String MSGHEADER = "【金蜂星】";
	public static boolean sendSms(String phone, String msg) {
		String resp = null;
		String charset = "utf-8";
		String account = "N3310414";
	    String password = "G5jcDwPdan751e";
		try {
			String smsSingleRequestServerUrl = "http://smssh1.253.com/msg/send/json";
			//String testbytes2 = new String(hexstr2bytes("0xF0 0x9F 0x8C 0xB9"),"utf-8");
			//msg = msg + testbytes2;
			String report= "false";
			String extend = "123";
			String uid = "abc123";
			String sendMsg = new String((MSGHEADER + msg).getBytes(),"utf-8");
	        SmsSendRequest smsSingleRequest = new SmsSendRequest(account, password, sendMsg, phone,report,extend);
			String requestJson = JSON.toJSONString(smsSingleRequest);
			log.info("before request string is: " + requestJson);
			resp = ChuangLanSmsUtil.sendSmsByPost(smsSingleRequestServerUrl, requestJson);
			log.info(resp);
			SmsSendResponse smsSingleResponse = JSON.parseObject(resp, SmsSendResponse.class);
			log.info("response toString is :" + smsSingleResponse);
			return true;
		} catch (Exception e) {
			log.error(e.toString());
			e.printStackTrace();
			return false;
		}
		
	}

    /**
     * 获取错误原因
     * @param nStatus int
     * @return String
     */
    private static String shiftStatus(int nStatus){
        String strStatus = "";
        switch(nStatus){
            case 100:
                strStatus = "余额不足";
                break;
            case 101:
                strStatus = "账号关闭";
                break;
            case 102:
                strStatus = "短信内容超过195字或为空或内容编码格式不正确";
                break;
            case 103:
                strStatus = "手机号码超过50个或合法的手机号码为空";
                break;
            case 104:
                strStatus = "用户访问时间间隔低于50毫秒";
                break;
            case 105:
                strStatus = "用户访问方式不是post方式";
                break;
            case 106:
                strStatus = "用户名不存在";
                break;
            case 107:
                strStatus = "密码错误";
                break;
            case 108:
                strStatus = "指定访问ip错误";
                break;
            case 110:
                strStatus = "小号不合法";
                break;
            case 111:
                strStatus = "短信内容内有敏感词";
                break;
           default:
               strStatus = "其他未知错误";
        }
        return strStatus;
    }

	@Override
	public SmsSendStatus sendSmsMsg(String mobileArea, String mobile, String smsContent, String templateKey) {
		SmsSendStatus sendStatus = SmsSendStatus.SUBMIT_OK;
		SmsTemplate template = smsTemplateBiz.selectByTemplateKey(templateKey);
		if(template==null || StringUtils.isBlank(template.getSmsTemplate())) {
			sendStatus = SmsSendStatus.TEMPLATE_ERR;
			return sendStatus;
		}

		boolean blFlag = sendSms(mobile, smsContent);
		if(!blFlag){
			sendStatus = SmsSendStatus.SUBMIT_ERR;
		} else {
			sendStatus = SmsSendStatus.SUBMIT_OK;
		}
		//写入发送日志
		SmsSendHis sysSmsSendHis = new SmsSendHis();
		sysSmsSendHis.setMobileArea(mobileArea);
		sysSmsSendHis.setMobileNo(mobile);
		sysSmsSendHis.setSubCode("");
		sysSmsSendHis.setBusiNote("");
		sysSmsSendHis.setMsgContent(smsContent);
		sysSmsSendHis.setReportNote("");
		sysSmsSendHis.setSendResult(sendStatus.description);
		sysSmsSendHis.setSendStatus((short) sendStatus.code);
		sysSmsSendHis.setSendTime(new Date());
		sysSmsSendHis.setTemplateId(template.getTemplateId());
		smsSendHisBiz.insertSelective(sysSmsSendHis);
		return sendStatus;
	}
}
